package com.chexiehui.jc.ui.activity;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.widget.TextView;

import com.aries.ui.widget.BasisDialog;
import com.aries.ui.widget.action.sheet.UIActionSheetDialog;
import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.Circle;
import com.baidu.mapapi.map.CircleOptions;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.Stroke;
import com.baidu.mapapi.model.LatLng;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.SizeUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chexiehui.jc.AppApplication;
import com.chexiehui.jc.Constants;
import com.chexiehui.jc.R;
import com.chexiehui.jc.base.BaseActivity;
import com.chexiehui.jc.utils.GPSUtil;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.Permission;
import com.yanzhenjie.permission.PermissionListener;
import com.yanzhenjie.permission.Rationale;
import com.yanzhenjie.permission.RationaleListener;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.annotations.NonNull;

/**
 * Author: SongJun.
 * CreateDate: 2018/10/25 0025.
 * Description: 地图activity
 */

public class MapLocationActivity extends BaseActivity {
    @BindView(R.id.mv_map_view)
    MapView mMapView;
    @BindView(R.id.tv_address_title)
    TextView mTvAddressTitle;
    private Marker myLocation;
    private Marker targetLocation;
    private LatLng myLatLng;
    private Circle accuracy;
    private UIActionSheetDialog mUIActionSheetDialog;
    private double currentLat = 0d;
    private double currentLng = 0d;
    private String currentStreet = "";
    private float mapLeave = 0;

    // 定位相关
    private BaiduMap mBaiduMap;

    @Override
    protected void beforeSetView() {
        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            currentLat = bundle.getDouble("latitude", 39.912057d);
            currentLng = bundle.getDouble("longitude", 116.404844d);
            mapLeave = bundle.getFloat("mapLeave", 0);
            currentStreet = bundle.getString("street", "");
        }
    }

    @Override
    protected void setTitleBar() {
        titleBar.setDividerVisible(false)
                .setLeftTextDrawable(R.drawable.ic_svg_back)
                .setStatusBarLightMode(true)
                .setBgColor(ContextCompat.getColor(mContext, R.color.colorTransparent));
    }

    protected int getLayout() {
        return R.layout.activity_map_loaction;
    }

    @Override
    protected void initView(Bundle var1) {
        mBaiduMap = mMapView.getMap();
        //隐藏地图上百度地图logo图标
        mMapView.removeViewAt(1);
        //隐藏地图上比例尺
        mMapView.showScaleControl(false);
        //隐藏缩放按钮
        mMapView.showZoomControls(false);
        // 开启定位图层
        mBaiduMap.setMyLocationEnabled(true);
        mTvAddressTitle.setText(currentStreet);
        if(currentLat > 0 && currentLng > 0){
            LatLng current = new LatLng(currentLat, currentLng);
            targetLocation = (Marker) mBaiduMap.addOverlay(new MarkerOptions().
                    position(current)
                    .icon(BitmapDescriptorFactory.fromResource(R.mipmap.ic_map_dtz))
                    .animateType(MarkerOptions.MarkerAnimateType.jump)
                    .anchor(0.5f, 0.5f));
            MapStatus.Builder builder = new MapStatus.Builder();
            builder.target(current).zoom(mapLeave > 0 ? mapLeave : 15.0f);
            mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        applyLocationPermission();
    }


    @OnClick({R.id.iv_dao_hang, R.id.iv_my_location,
            R.id.tv_address_title
    })
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_dao_hang:
                if (mUIActionSheetDialog == null) {
                    initSheetAction();
                }
                mUIActionSheetDialog.show();
                break;
            case R.id.iv_my_location:
                if (myLatLng != null) {
                    MapStatus.Builder builder = new MapStatus.Builder();
                    builder.target(myLatLng).zoom(15.0f);
                    mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
                }
                break;
            default:
                if (currentLat > 0 && currentLng > 0) {
                    LatLng current = new LatLng(currentLat, currentLng);
                    if (targetLocation == null) {
                        targetLocation = (Marker) mBaiduMap.addOverlay(new MarkerOptions().
                                position(current)
                                .icon(BitmapDescriptorFactory.fromResource(R.mipmap.ic_map_dtz))
                                .animateType(MarkerOptions.MarkerAnimateType.jump)
                                .anchor(0.5f, 0.5f));
                    }
                    MapStatus.Builder builder = new MapStatus.Builder();
                    builder.target(current).zoom(mapLeave > 0 ? mapLeave : 15.0f);
                    mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
                }
                break;
        }
    }

    private void initSheetAction() {
        if(currentLat <= 0 || currentLng <= 0){
            return;
        }
        mUIActionSheetDialog = new UIActionSheetDialog.ListIOSBuilder(this)
                .addItems(R.array.arrays_navigation_mode)
                .setItemsTextColorResource(R.color.colorActionSheetItemText)
                .setTitle(getString(R.string.string_xzdt))
                .setCancel(R.string.cancel)
                .setCancelMarginTop(SizeUtils.dp2px(10))
                .setCancelTextColorResource(android.R.color.darker_gray)
                .setOnItemClickListener(new UIActionSheetDialog.OnItemClickListener() {
                    @Override
                    public void onClick(BasisDialog dialog, View itemView, int position) {
                        switch (position){
                            case 0:
                                GPSUtil.gotoTengxun(MapLocationActivity.this, currentStreet,
                                        currentLat, currentLng);
                                break;
                            case 1:
                                GPSUtil.goToNaviActivity(MapLocationActivity.this, currentStreet,
                                        currentLat, currentLng);
                                break;
                            case 2:
                                GPSUtil.goToBaiduActivity(MapLocationActivity.this, currentStreet,
                                        currentLat, currentLng);
                                break;
                        }
                    }
                })
                .setBackgroundRadius(10)
                .create()
                .setDimAmount(0.5f)
                .setAlpha(1f);
    }

    private void applyLocationPermission() {
        AndPermission.with(this)
                .permission(Permission.LOCATION)
                .callback(new PermissionListener() {
                    @Override
                    public void onSucceed(int requestCode, @NonNull List<String> grantPermissions) {
                        if (!AppApplication.getInstances().getLocationService().isStart()) {
                            AppApplication.getInstances().getLocationService().start();
                        }
                        AppApplication.getInstances().getLocationService().registerListener(mListener);
                    }

                    @Override
                    public void onFailed(int requestCode, @NonNull List<String> deniedPermissions) {
                        // 用户否勾选了不再提示并且拒绝了权限，那么提示用户到设置中授权。
                        if (AndPermission.hasAlwaysDeniedPermission(mContext, deniedPermissions)) {
                            // 第一种：用默认的提示语。
                            AndPermission.defaultSettingDialog(mContext, Constants.REQUEST_CODE_LOACTION).show();
                        } else {
                            ToastUtils.showShort("请在权限管理中开启位置权限");
                        }
                    }
                })
                .requestCode(Constants.REQUEST_CODE_LOACTION)
                .rationale(new RationaleListener() {
                    @Override
                    public void showRequestPermissionRationale(int requestCode, Rationale rationale) {
                        // 这里的对话框可以自定义，只要调用rationale.resume()就可以继续申请。
                        AndPermission.rationaleDialog(mContext, rationale).show();
                    }
                }).start();
    }

    private BDAbstractLocationListener mListener = new BDAbstractLocationListener() {
        @Override
        public void onReceiveLocation(BDLocation location) {
            if (null != location && location.getLocType() != BDLocation.TypeServerError) {
                LogUtils.e("home-----------------:" + location.getAddrStr());
                if(!StringUtils.isTrimEmpty(location.getCity()) || isFinish()){
                    Message msg = new Message();
                    msg.obj = location;
                    msg.what = 0;
                    handler.sendMessage(msg);
                }
            }
        }

        @Override
        public void onConnectHotSpotMessage(String s, int i) {
            super.onConnectHotSpotMessage(s, i);
        }

        @Override
        public void onLocDiagnosticMessage(int locType, int diagnosticType, String diagnosticMessage) {
            super.onLocDiagnosticMessage(locType, diagnosticType, diagnosticMessage);
        }
    };



    @Override
    protected void onDestroy() {
        // 退出时销毁定位
        handler.removeCallbacksAndMessages(null);
        handler = null;
        AppApplication.getInstances().getLocationService().unregisterListener(mListener);
        mListener = null;
        // 关闭定位图层
        mBaiduMap.setMyLocationEnabled(false);
        mMapView.onDestroy();
        if(myLocation != null){
            myLocation.remove();
            myLocation = null;
        }
        if(accuracy != null){
            accuracy.remove();
            accuracy = null;
        }
        myLatLng = null;
        mMapView = null;
        super.onDestroy();
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 0) {
                BDLocation location = (BDLocation) msg.obj;
                myLatLng = new LatLng(location.getLatitude(), location.getLongitude());

                if (myLocation == null) {
                    MarkerOptions option = new MarkerOptions()
                            .position(myLatLng)
                            .icon(BitmapDescriptorFactory.fromResource(R.mipmap.ic_my_location))
                            .zIndex(9) // 设置marker所在层级
                            .draggable(true); // 设置手势拖拽

                    //在地图上添加Marker，并显示
                    myLocation = (Marker) mBaiduMap.addOverlay(option);
                }

                if (accuracy == null) {
                    CircleOptions oc = new CircleOptions().
                            center(myLatLng).
                            radius((int) location.getRadius()).
                            fillColor(0x440000ff).
                            stroke(new Stroke(1, 0x440000ff));
                    accuracy = (Circle) mBaiduMap.addOverlay(oc);
                }
                myLocation.setPosition(myLatLng);
                accuracy.setCenter(myLatLng);
                accuracy.setRadius((int) location.getRadius());
            }
        }
    };

}
